import { useState, useEffect } from 'react';
import { Typography, Spin, message, Card, Row, Col, Avatar, Empty, Space, ConfigProvider, Button, Modal } from 'antd';
import { EyeOutlined, ReloadOutlined, ShoppingCartOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { motion } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import { getOpenDraftList } from '@/services/project';
import { getCurrentUser, purchaseTemplate } from '@/services/api';
import '@/styles/create-project/index.css';

const { Title, Text, Paragraph } = Typography;
const { Meta } = Card;

// 暗色主题样式配置
const darkThemeStyles = {
    card: {
        backgroundColor: '#1f1f1f',
        borderColor: '#303030',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.3)',
    },
    text: {
        primary: '#ffffff',
        secondary: 'rgba(255, 255, 255, 0.65)',
        tertiary: 'rgba(255, 255, 255, 0.45)',
    },
    cover: {
        backgroundColor: '#2a2a2a',
        textColor: '#177ddc',
    },
    avatar: {
        backgroundColor: '#177ddc',
        color: '#ffffff',
    },
    empty: {
        backgroundColor: '#2a2a2a',
        borderColor: '#303030',
    },
};

// 定义公开草稿的类型
interface PublicDraft {
    id: string;
    name: string;
    creator: string;
    detail: string;
    jianying_json: string;
    points_cost: number;
    created_id: number;
    preview_video_url: string;
    [key: string]: any;
}

// 模板市场组件
const TemplateList = () => {
    const [drafts, setDrafts] = useState<PublicDraft[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [currentUserId, setCurrentUserId] = useState<number | null>(null);
    const [purchasingIds, setPurchasingIds] = useState<Set<string>>(new Set());
    const [previewModalVisible, setPreviewModalVisible] = useState(false);
    const [previewVideoUrl, setPreviewVideoUrl] = useState<string>('');
    const [previewTemplateName, setPreviewTemplateName] = useState<string>('');
    const navigate = useNavigate();

    // 加载公开草稿列表
    const fetchDrafts = async () => {
        setLoading(true);
        try {
            const response = await getOpenDraftList();
            if (!response.data.drafts) {
                return;
            }
            setDrafts(response.data.drafts);
        } catch (error) {
            message.error('获取公开草稿失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取当前用户信息
    const fetchCurrentUser = async () => {
        try {
            const userData = await getCurrentUser();
            setCurrentUserId(userData.user_id);
        } catch (error) {
            console.error('获取用户信息失败:', error);
        }
    };

    useEffect(() => {
        fetchDrafts();
        fetchCurrentUser();
    }, []);

    // 处理卡片点击事件 - 跳转到编辑器页面
    const handleCardClick = (draft: PublicDraft) => {
        console.log(`draft=>`, draft);
        navigate(`/editor?draftId=${draft.id}`);
    };

    // 处理购买按钮点击事件
    const handlePurchase = async (draft: PublicDraft, event: React.MouseEvent) => {
        event.stopPropagation(); // 阻止事件冒泡，避免触发卡片点击

        try {
            // 添加到购买中的ID集合
            setPurchasingIds((prev) => new Set(prev).add(draft.id));

            // 调用购买接口
            const response = await purchaseTemplate({ template_id: draft.id });

            if (response.success) {
                message.success(`成功购买模板 "${draft.name}"，已创建草稿副本`);
                // 购买成功后刷新列表
                await fetchDrafts();
            } else {
                message.error(response.message || '购买失败');
            }
        } catch (error: any) {
            console.error('购买模板失败:', error);
            const errorMessage = error?.response?.data?.message || error?.message || '购买失败，请稍后重试';
            message.error(errorMessage);
        } finally {
            // 从购买中的ID集合移除
            setPurchasingIds((prev) => {
                const newSet = new Set(prev);
                newSet.delete(draft.id);
                return newSet;
            });
        }
    };

    // 判断是否显示购买按钮
    const shouldShowPurchaseButton = (draft: PublicDraft) => {
        console.log('draft', draft);
        console.log('currentUserId', currentUserId);
        return currentUserId !== null && draft.created_id !== currentUserId;
    };

    // 打开视频预览模态框
    const openPreviewModal = (draft: PublicDraft, event: React.MouseEvent) => {
        event.stopPropagation(); // 阻止事件冒泡，避免触发卡片点击
        setPreviewVideoUrl(draft.preview_video_url);
        setPreviewTemplateName(draft.name);
        setPreviewModalVisible(true);
    };

    // 关闭视频预览模态框
    const closePreviewModal = () => {
        setPreviewModalVisible(false);
        setPreviewVideoUrl('');
        setPreviewTemplateName('');
    };

    // 自定义卡片封面
    const renderCardCover = (draft: PublicDraft) => {
        // 如果有预览视频，显示视频；否则显示默认的渐变背景
        if (draft.preview_video_url) {
            return (
                <div
                    style={{
                        height: 120,
                        position: 'relative',
                        borderTopLeftRadius: 8,
                        borderTopRightRadius: 8,
                        overflow: 'hidden',
                        backgroundColor: '#000',
                    }}
                >
                    <video
                        src={draft.preview_video_url}
                        style={{
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover',
                        }}
                        muted
                        loop
                        playsInline
                        preload="metadata"
                    />
                    <div
                        style={{
                            position: 'absolute',
                            top: 0,
                            left: 0,
                            right: 0,
                            bottom: 0,
                            background: 'linear-gradient(45deg, rgba(0,0,0,0.3) 0%, rgba(0,0,0,0.1) 100%)',
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                        }}
                    >
                        <div
                            style={{
                                fontSize: 28,
                                fontWeight: 600,
                                color: darkThemeStyles.text.primary,
                                opacity: 0.9,
                                textShadow: '0 2px 4px rgba(0, 0, 0, 0.8)',
                            }}
                        >
                            {draft.name.charAt(0)}
                        </div>
                    </div>
                    <Avatar
                        icon={<EyeOutlined />}
                        size="small"
                        style={{
                            position: 'absolute',
                            top: 8,
                            right: 8,
                            backgroundColor: 'rgba(0, 0, 0, 0.6)',
                            color: darkThemeStyles.text.primary,
                            boxShadow: '0 2px 4px rgba(0, 0, 0, 0.3)',
                            border: '1px solid rgba(255, 255, 255, 0.2)',
                        }}
                    />
                </div>
            );
        }

        // 默认的渐变背景
        const gradientColors = draft.id.charCodeAt(0) % 2 === 0 ? 'linear-gradient(135deg, #1a365d 0%, #0f2942 100%)' : 'linear-gradient(135deg, #003a70 0%, #001a33 100%)';

        return (
            <div
                style={{
                    height: 120,
                    background: gradientColors,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    position: 'relative',
                    borderTopLeftRadius: 8,
                    borderTopRightRadius: 8,
                }}
            >
                <div
                    style={{
                        fontSize: 28,
                        fontWeight: 600,
                        color: darkThemeStyles.text.primary,
                        opacity: 0.9,
                        textShadow: '0 2px 4px rgba(0, 0, 0, 0.3)',
                    }}
                >
                    {draft.name.charAt(0)}
                </div>
                <Avatar
                    icon={<EyeOutlined />}
                    size="small"
                    style={{
                        position: 'absolute',
                        top: 8,
                        right: 8,
                        backgroundColor: 'rgba(255, 255, 255, 0.15)',
                        color: darkThemeStyles.text.primary,
                        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
                    }}
                />
            </div>
        );
    };

    return (
        <ConfigProvider
            theme={{
                components: {
                    Card: {
                        colorBgContainer: darkThemeStyles.card.backgroundColor,
                        colorBorderSecondary: darkThemeStyles.card.borderColor,
                    },
                    Typography: {
                        colorText: darkThemeStyles.text.primary,
                        colorTextSecondary: darkThemeStyles.text.secondary,
                    },
                    Spin: {
                        colorPrimary: '#177ddc',
                    },
                    Empty: {
                        colorText: darkThemeStyles.text.secondary,
                    },
                },
            }}
        >
            <Card
                variant="borderless"
                style={{
                    marginBottom: 24,
                    backgroundColor: darkThemeStyles.card.backgroundColor,
                    boxShadow: darkThemeStyles.card.boxShadow,
                }}
                styles={{ body: { padding: 32 } }}
            >
                <Space direction="vertical" size={32} style={{ width: '100%' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                        <div>
                            <Title
                                level={4}
                                style={{
                                    marginBottom: 8,
                                    fontWeight: 600,
                                    color: darkThemeStyles.text.primary,
                                }}
                            >
                                公开草稿模板
                            </Title>
                            <Text style={{ color: darkThemeStyles.text.secondary }}>探索社区分享的优质模板，一键应用快速开始创作</Text>
                        </div>
                        <Button
                            icon={<ReloadOutlined />}
                            onClick={fetchDrafts}
                            loading={loading}
                            style={{
                                color: darkThemeStyles.text.secondary,
                                backgroundColor: 'transparent',
                                border: '1px solid rgba(255, 255, 255, 0.15)',
                            }}
                        >
                            刷新
                        </Button>
                    </div>

                    <Spin spinning={loading} tip="加载模板中...">
                        {drafts.length === 0 ? (
                            <Empty
                                description={
                                    <span
                                        style={{
                                            color: darkThemeStyles.text.secondary,
                                        }}
                                    >
                                        暂无公开草稿模板
                                    </span>
                                }
                                style={{
                                    backgroundColor: darkThemeStyles.empty.backgroundColor,
                                    padding: '60px 20px',
                                    borderRadius: 8,
                                    border: `1px dashed ${darkThemeStyles.empty.borderColor}`,
                                }}
                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                            />
                        ) : (
                            <Row gutter={[24, 24]}>
                                {drafts.map((draft) => (
                                    <Col xs={24} sm={12} md={8} lg={8} xl={6} key={`template-${draft.id}`}>
                                        <motion.div
                                            whileHover={{
                                                scale: 1.02,
                                                boxShadow: '0 8px 24px rgba(0, 0, 0, 0.3)',
                                                y: -4,
                                            }}
                                            whileTap={{ scale: 0.98 }}
                                        >
                                            <Card
                                                hoverable
                                                cover={renderCardCover(draft)}
                                                onClick={() => handleCardClick(draft)}
                                                style={{
                                                    backgroundColor: darkThemeStyles.card.backgroundColor,
                                                    borderColor: darkThemeStyles.card.borderColor,
                                                    borderRadius: 8,
                                                    overflow: 'hidden',
                                                }}
                                                styles={{
                                                    body: {
                                                        padding: 20,
                                                        minHeight: 180,
                                                        backgroundColor: darkThemeStyles.card.backgroundColor,
                                                    },
                                                }}
                                            >
                                                <Space direction="vertical" size={12} style={{ width: '100%' }}>
                                                    <Text
                                                        strong
                                                        ellipsis
                                                        style={{
                                                            fontSize: 16,
                                                            color: darkThemeStyles.text.primary,
                                                        }}
                                                    >
                                                        {draft.name}
                                                    </Text>

                                                    <Paragraph
                                                        ellipsis={{ rows: 2 }}
                                                        style={{
                                                            fontSize: 14,
                                                            color: darkThemeStyles.text.secondary,
                                                            margin: 0,
                                                        }}
                                                    >
                                                        {draft.detail || '该模板暂无描述'}
                                                    </Paragraph>

                                                    <div
                                                        style={{
                                                            marginTop: 'auto',
                                                        }}
                                                    >
                                                        {/* 用户信息和积分信息行 */}
                                                        <div
                                                            style={{
                                                                display: 'flex',
                                                                justifyContent: 'space-between',
                                                                alignItems: 'center',
                                                                marginBottom: '12px',
                                                            }}
                                                        >
                                                            <Meta
                                                                avatar={
                                                                    <Avatar
                                                                        size="small"
                                                                        style={{
                                                                            backgroundColor: '#177ddc',
                                                                            color: '#ffffff',
                                                                            border: '2px solid rgba(255, 255, 255, 0.2)',
                                                                        }}
                                                                    >
                                                                        {draft.creator.charAt(0).toUpperCase()}
                                                                    </Avatar>
                                                                }
                                                                title={null}
                                                                description={
                                                                    <Text
                                                                        style={{
                                                                            fontSize: 13,
                                                                            color: darkThemeStyles.text.tertiary,
                                                                        }}
                                                                    >
                                                                        {draft.creator}
                                                                    </Text>
                                                                }
                                                            />
                                                            <Text
                                                                style={{
                                                                    fontSize: 14,
                                                                    color: '#52c41a',
                                                                    fontWeight: 600,
                                                                    backgroundColor: 'rgba(82, 196, 26, 0.1)',
                                                                    padding: '4px 8px',
                                                                    borderRadius: '4px',
                                                                    border: '1px solid rgba(82, 196, 26, 0.3)',
                                                                }}
                                                            >
                                                                {draft.points_cost || 0} 积分
                                                            </Text>
                                                        </div>

                                                        {/* 预览和购买按钮行 */}
                                                        <div
                                                            style={{
                                                                display: 'flex',
                                                                gap: '8px',
                                                                marginTop: '8px',
                                                            }}
                                                        >
                                                            {/* 预览按钮 - 只有有预览视频时才显示 */}
                                                            {draft.preview_video_url && (
                                                                <motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }} style={{ flex: 1 }}>
                                                                    <Button
                                                                        type="default"
                                                                        size="small"
                                                                        icon={<PlayCircleOutlined />}
                                                                        onClick={(e) => openPreviewModal(draft, e)}
                                                                        block
                                                                        style={{
                                                                            backgroundColor: '#1890ff',
                                                                            borderColor: '#1890ff',
                                                                            color: '#ffffff',
                                                                            fontSize: '13px',
                                                                            height: '36px',
                                                                            fontWeight: 500,
                                                                        }}
                                                                    >
                                                                        预览视频
                                                                    </Button>
                                                                </motion.div>
                                                            )}

                                                            {/* 购买按钮 */}
                                                            {shouldShowPurchaseButton(draft) && (
                                                                <motion.div whileHover={{ scale: 1.02 }} whileTap={{ scale: 0.98 }} style={{ flex: 1 }}>
                                                                    <Button
                                                                        type="primary"
                                                                        size="small"
                                                                        icon={<ShoppingCartOutlined />}
                                                                        onClick={(e) => handlePurchase(draft, e)}
                                                                        loading={purchasingIds.has(draft.id)}
                                                                        block
                                                                        style={{
                                                                            backgroundColor: '#ff4d4f',
                                                                            borderColor: '#ff4d4f',
                                                                            fontSize: '13px',
                                                                            height: '36px',
                                                                            fontWeight: 500,
                                                                        }}
                                                                    >
                                                                        {purchasingIds.has(draft.id) ? '购买中...' : '购买模板'}
                                                                    </Button>
                                                                </motion.div>
                                                            )}
                                                        </div>
                                                    </div>
                                                </Space>
                                            </Card>
                                        </motion.div>
                                    </Col>
                                ))}
                            </Row>
                        )}
                    </Spin>
                </Space>
            </Card>

            {/* 视频预览模态框 */}
            <style>
                {`
                    .video-preview-modal .ant-modal-close {
                        color: ${darkThemeStyles.text.primary} !important;
                    }
                    .video-preview-modal .ant-modal-close:hover {
                        color: #ff4d4f !important;
                    }
                    .video-preview-modal .ant-modal-close .ant-modal-close-x {
                        color: ${darkThemeStyles.text.primary} !important;
                    }
                    .video-preview-modal .ant-modal-close .ant-modal-close-x:hover {
                        color: #ff4d4f !important;
                    }
                `}
            </style>
            <ConfigProvider
                theme={{
                    components: {
                        Modal: {
                            contentBg: darkThemeStyles.card.backgroundColor,
                            headerBg: darkThemeStyles.card.backgroundColor,
                            titleColor: darkThemeStyles.text.primary,
                            colorText: darkThemeStyles.text.primary,
                        },
                    },
                }}
            >
                <Modal
                    title={<div style={{ color: darkThemeStyles.text.primary, fontSize: '18px', fontWeight: 600 }}>🎥 预览视频 - {previewTemplateName}</div>}
                    open={previewModalVisible}
                    onCancel={closePreviewModal}
                    footer={null}
                    width={800}
                    centered
                    className="video-preview-modal"
                    styles={{
                        header: {
                            background: darkThemeStyles.card.backgroundColor,
                            borderBottom: `1px solid ${darkThemeStyles.card.borderColor}`,
                        },
                        body: {
                            background: darkThemeStyles.card.backgroundColor,
                            padding: '24px',
                        },
                        mask: {
                            backdropFilter: 'blur(4px)',
                        },
                    }}
                    style={{
                        color: darkThemeStyles.text.primary,
                    }}
                >
                    {previewVideoUrl && (
                        <div
                            style={{
                                position: 'relative',
                                width: '100%',
                                height: '450px',
                                backgroundColor: '#000',
                                borderRadius: '8px',
                                overflow: 'hidden',
                                boxShadow: '0 4px 12px rgba(0, 0, 0, 0.3)',
                            }}
                        >
                            <video
                                src={previewVideoUrl}
                                style={{
                                    width: '100%',
                                    height: '100%',
                                    objectFit: 'contain',
                                }}
                                controls
                                autoPlay
                                preload="metadata"
                            />
                        </div>
                    )}

                    <div
                        style={{
                            marginTop: '16px',
                            textAlign: 'center',
                            color: darkThemeStyles.text.secondary,
                            fontSize: '14px',
                        }}
                    >
                        点击视频可全屏播放，按 ESC 键退出全屏
                    </div>
                </Modal>
            </ConfigProvider>
        </ConfigProvider>
    );
};

export default TemplateList;
